import Rte from 'editor/index'
import { RteCommandProp } from 'editor/command/declate'
import DroplistMenu from './droplist/droplist'
import ButtonMenu from './button/button'
import menuList from './menus'
import DelimiterMenu from './delimiter/delimiter'
import { DroplistMenuConfig, MenuConfig, MenuInstance, MenuType, SelectionMenuConfig } from './declare'

export default class RteMenu {
  /**
   * 菜单栏配置
   */
  public config: MenuConfig[] = menuList()

  public margin: string = '5px'

  /**
   * 根据配置生成的对应实例
   */
  public instance: MenuInstance[] = []

  public constructor(public editor: Rte) {
    editor.$moniter.$once('mount', () => {
      this.$mount()
    })
  }

  /**
   * 根据菜单栏配置进行实例初始化
   */
  public $mount() {
    if (!this.instance.length) {
      this.config.forEach((menu) => {
        switch (menu.type) {
          case MenuType.BUTTON:
            this.mountButton(menu.command)
            break
          case MenuType.DROPLIST:
          case MenuType.SELECTION:
            this.mountDroplist(menu)
            break
          case MenuType.DELIMITER:
            this.mountDelimiter()
            break
          default:
            break
        }
      })
      this.instance[0].$refs.root.style.setProperty('margin-left', this.margin)
    }
  }

  public $destory() {
    this.instance.forEach((instance) => instance.$refs.root.remove())
    this.instance.length = 0
  }

  public mountButton(command: RteCommandProp) {
    const icon = this.editor.icon[command] || ''
    const instance = new ButtonMenu(this.editor, command, icon)
    this.saveInstace(instance)
    return instance
  }

  public mountDroplist(config: DroplistMenuConfig | SelectionMenuConfig) {
    const instance = new DroplistMenu(this.editor, config)
    this.saveInstace(instance)
    return instance
  }

  public mountDelimiter() {
    const instance = new DelimiterMenu(this.editor)
    instance.$refs.root.style.setProperty('margin', `0 ${this.margin} 0`)
    this.saveInstace(instance)
    return instance
  }

  private saveInstace(instance: MenuInstance) {
    this.instance.push(instance)
    this.editor.$refs.toolbar.appendChild(instance.$refs.root)
  }
}
